<?php
// +----------------------------------------------------------------------
// | 有理想的地方，地狱都是天堂。
// +----------------------------------------------------------------------
// | Copyright @ df81.com 版权所有
// +----------------------------------------------------------------------
// | 作者: 南国老符 邮箱：1062129401@qq.com
// +----------------------------------------------------------------------

namespace app\admin\controller;
use app\admin\model\Module as moduleModel;
use app\admin\model\Project as projectModel;
use app\admin\model\Area as areaModel;
use app\admin\validate\Project as projectValidate;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\View;

class Project extends Base{
    // 添加编辑
    public function edit($id=0){
        // 转为小写字母
        $general = new \common\General();
        $tabledir = $general->capital_to_underline(input('tabledir'));
		
		$rs = Db::name($tabledir)->where('id',$id)->find();
        // 格式化属性值
        $rs['attvalue'] = json_decode($rs['attvalue'],true);
        $attvalueArr = array();
        foreach ($rs['attvalue'] as $v) {
            $vArr = explode('：',$v);
            $attvalueArr[] = array($vArr[0],unicode2Chinese($vArr[2]));
        }
        $rs['attvalue'] = $attvalueArr;
        View::assign('rs',$rs);

        // 父级标题
        $tree_title = '';
        if(!empty($rs)){
            $sortRs = Db::name('sort')->field('title')->where('id',$rs['sortid'])->find();
            $tree_title = $sortRs['title'];
        }
        View::assign('tree_title',$tree_title);
        View::assign('tabledir',$tabledir);

        if(!request()->isPost()){
			// 更多图片更多附件
            $morefilesNum = $morepicsNum = 2;
            if(!empty($rs['morepics'])){
                $img_array = explode('|',$rs['morepics']);
                View::assign('morepics',$img_array);
                $morepicsNum = count($img_array)-1;
            }
            View::assign('morepicsNum',$morepicsNum);
            if(!empty($rs['morefileurl'])){
                $file_array = explode('|',$rs['morefileurl']);
                View::assign('morefileurl',$file_array);
                $morefilesNum = count($file_array)-1;
            }
            View::assign('morefilesNum',$morefilesNum);

            // 分类赋值
            $langWhere[] = ['lang','=',$this->lang]; $langWhere[] = ['signid','=',1]; $sortWhere[] = ['tabledir','=',$tabledir];
            View::assign('sort',getChildSort(Db::name('sort')->where($sortWhere)->where($langWhere)->field('id,parentid,title,short_title')->order('sequence desc,id desc')->select()));

            // 地区赋值
            View::assign('area',getChildSort(Db::name('area')->where($langWhere)->field('id,title')->order('sequence desc,id desc')->select()));

            // 品牌赋值
            View::assign('brand',Db::name('brand')->where($langWhere)->field('id,title')->order('sequence desc,id desc')->select());
			
			/*
		    //地区
			$areaArr = json_encode(getAreaArr('Area',0,$this->lang));
            View::assign('areaArr',$areaArr);
		    //编辑信息时获取地区ID
			$a = ""; $b = ""; $c = ""; $d = "";
            $areaRs =  getParentSort(Db::name('area')->select(),$rs['areaid']);
			foreach($areaRs as $k => $v){
				$abcd = $v['id'];
				switch($k){
                    case 0:
		                $a = $abcd;
                        break;
                    case 1:
		                $b = $abcd;
                        break;
                    case 2:
		                $c = $abcd;
                        break;
                    case 3:
		                $d = $abcd;
                        break;
                }
			}
			View::assign('a',$a); View::assign('b',$b); View::assign('c',$c); View::assign('d',$d);
			*/

            // 加载前端配置文件
            $langConfig = app()->getBasePath().$this->lang.DS.'config'.DS.'template.php';
            $configArray = include_once($langConfig);
            
            //前端详情页模板
            $suffix = config('view.view_suffix');
            $templatePath = app()->getRootPath().'template/'.$configArray['theme'].'/pc/'.$tabledir.'/';
            $templateList = array();
            if(is_dir($templatePath)){
                $dofile = new \common\Dofile();
                $templateArr = $dofile->getFiles($templatePath,false,$suffix);
                foreach ($templateArr as $preTempRs) {
                    if(strpos($preTempRs,'view_') !== false){
                        $templateList[] = $preTempRs;
                    }
                }
            }
            View::assign('viewtemp',$templateList);
            View::assign('defaulttemp',"view_default");

            //模块信息
            $moduleWhere[] = ['lang','=',$this->lang]; $moduleWhere[] = ['tabledir','=',$tabledir];
            $moduleRs = Db::name('module')->where($moduleWhere)->find();
            View::assign('mRs',$moduleRs);

            // 属性列表
            $attWhere[] = ['tabledir','=',$tabledir]; $attWhere[] = ['parentid','=',0]; $attWhere[] = ['lang','=',$this->lang];
            $attlist = Db::name('attribute')->where($attWhere)->order('sequence desc,id desc')->select()
                    ->each(function($item, $key){
                        if(in_array($item['fieldtype'],array('radio','checkbox'))){
                            $item['attvalue'] = explode(PHP_EOL,$item['attvalue']);
                        }
                        return $item;
                    });
            View::assign('attlist',$attlist);

            //规格属性
            $specattWhere[] = ['tabledir','=','Shop_spec']; $specattWhere[] = ['parentid','=',0];
            $specattWhere[] = ['lang','=',$this->lang]; $specattWhere[] = ['attvalue','=',$tabledir];
            View::assign('specatt',Db::name('attribute')->where($specattWhere)->order('sequence desc,id desc')->select());

            //标签
            View::assign('module_tags',explode(PHP_EOL,$moduleRs['tags']));
            View::assign('tags',explode(',',$rs['tags']));

            //随机初始点击数
            $hits = 1;
            $initialhitsArr = explode(',', $this->navModuleRs['initial_hits']);
            if(count($initialhitsArr) == 2){
                if($initialhitsArr[0] > 0 and $initialhitsArr[1] > $initialhitsArr[0]){
                    $hits =  rand($initialhitsArr[0],$initialhitsArr[1]);
                }
            }
            View::assign('hits',$hits);
            
            // 所属地区
            $city_title = '';
            if(!empty($rs['cityid'])){
                $cityList = Db::name('area')->where('id','in',$rs['cityid'])->field('title')->select();
                foreach ($cityList as $cityRs){
                    $city_title .= $cityRs['title'].',';
                }
            }
            $city_title = rtrim($city_title,',');
            View::assign('city_title',$city_title);
            
            //初始库存
            $stock = 1000000;
            if(!empty($this->navModuleRs['initial_stock']) and is_numeric($this->navModuleRs['initial_stock'])){
                $stock = $this->navModuleRs['initial_stock'];
            }
            View::assign('stock',$stock);
            //库存单位
            View::assign('stockunit_arr',explode(PHP_EOL, $this->navModuleRs['stockunit']));

            return view();
        }else{
            //分类是否存在
            // $haveSortWhere[] = ['tabledir','=',$tabledir]; $haveSortWhere[] = ['lang','=',$this->lang];
            // $isSort = Db::name('sort')->where($haveSortWhere)->find();
            // if(empty($isSort)){
            //     return json(['code' => 1001, 'msg' => lang('c_add_first').lang('v_sort'), 'data' => '']);
            // }

            //地区是否存在
            // $isArea = Db::name('area')->where('lang',$this->lang)->find();
            // if(empty($isArea)){
            //     return json(['code' => 1002, 'msg' => lang('c_add_first').lang('v_area'), 'data' => '']);
            // }

            // 表单验证
            try {
                validate(projectValidate::class)->check(input('post.'));
            } catch (ValidateException $e) {
                return json(['code' => 1003, 'msg' => $e->getMessage(), 'data' => '']);
            }

            // 语言目录下信息url唯一性验证
            $urlroute = input('urlroute');
            $urlWhere[] = ['lang','=',$this->lang]; $urlWhere[] = ['urlroute','=',$urlroute];
            $infoUrl = Db::name($tabledir)->where($urlWhere)->count();
            if($infoUrl >= 1 and input('urlroute') != $rs['urlroute']){
                return json(['code' => 1004, 'msg' => lang('v_urlroute_tips'), 'data' => '']);
            }

            try {
                projectModel::edit($tabledir,$id);
                return json(['code' => 200, 'msg' => lang('c_success'), 'data' => array('id'=>$id)]);
            } catch (Exception $e) {
                return json(['code' => 500, 'msg' => $e->getMessage(), 'data' => '']);
            }
        }		
	}

    // 列表
    public function index($keyword=""){
        $signid = input('signid'); $tabledir = input('tabledir'); $sortid = input('sortid');
        $field = '*'; $keyword = input('keyword'); $order = ['id'=>'desc','addtime'=>'desc'];

        $general = new \common\General();
        $tabledir = $general->capital_to_underline($tabledir);

        if(empty($signid)) $signid = 1;
		$rs = moduleModel::infoList($tabledir,$sortid,$this->lang,20,$field,$keyword,$order,$signid);

        //1上架2下架9已删除，大于9就是删除时间戳
        View::assign('signid',$signid);

        //模块信息
        $moduleWhere[] = ['lang','=',$this->lang]; $moduleWhere[] = ['tabledir','=',$tabledir];
        $moduleRs = Db::name('module')->where($moduleWhere)->find();
        View::assign('mRs',$moduleRs);

		View::assign('list',$rs);
		View::assign('total',$rs->total());
		View::assign('lastPage',$rs->lastPage());
		
        return view();
    }
}